package com.easa.controller;

import com.alibaba.fastjson.JSONObject;
import com.easa.entity.ShowTeacherMsg;
import com.easa.entity.Teachermsg;
import com.easa.service.TeacherMsgService;
import com.easa.util.MD5Utils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.management.relation.Role;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherMsgController  {

    @Autowired
    private TeacherMsgService teacherMsgService;

    /*注册*/
    @RequestMapping(value="register",method= RequestMethod.POST)
    @ResponseBody
    public Object setTeacherMsg(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        String userName = request.getParameter("userName");

        Teachermsg teachermsg = new Teachermsg();
        teachermsg.setTid(userId);
        teachermsg.setPassword(password);
        teachermsg.setTname(userName);

        //返回0成功，1出错，2冲突
        int isSuccess = teacherMsgService.insertTeacherMsg(teachermsg);
        js.put("isSuccess", isSuccess);
        return js;
    }

    /*登录*/
    @RequestMapping(value="loginValidate",method= RequestMethod.POST)
    @ResponseBody
    public Object loginValidate(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");

        System.out.println("userId:"+userId+"\n"+"password:"+password);
        //返回0成功，1账号不存在，2密码不正确,3账号未被激活
        int isSuccess = teacherMsgService.loginValidate(userId,password);
        System.out.println("isSuccess:"+isSuccess);
        js.put("isSuccess", isSuccess);
        return js;
    }

    /*获取个人信息*/
    @RequestMapping(value="getPersonalMsg",method= RequestMethod.POST)
    @ResponseBody
    public Object getPersonalMsg(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String userId = request.getParameter("userId");
        ShowTeacherMsg teachermsg = teacherMsgService.findTeacherMsgByid(userId);
        js.put("personalMsg", teachermsg);
        return js;
    }

    /*更新个人信息*/
    @RequestMapping(value="updatePersonData",method= RequestMethod.POST)
    @ResponseBody
    public Object updatePersonData(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String userId = request.getParameter("userId");
        String userName = request.getParameter("userName");
        String contactWay = request.getParameter("phone");
        String professinalTitle = request.getParameter("professinalTitle");
        Teachermsg teachermsg = new Teachermsg();
        teachermsg.setTid(userId);
        teachermsg.setTname(userName);
        teachermsg.setContactWay(contactWay);
        teachermsg.setProfessinalTitle(professinalTitle);
        Boolean isSuccess = teacherMsgService.updateTeacherMsg(teachermsg);
        JSONObject js = new JSONObject();
        js.put("isSuccess", isSuccess);
        return js;
    }

    /*登录*/
    @RequestMapping(value="loginSubmit",method= RequestMethod.POST)
    @ResponseBody
    public Object validateAdmin(HttpServletRequest request, HttpServletResponse response){
        String userId = request.getParameter("userId");
        String pass = request.getParameter("password");
        int isSuccess = teacherMsgService.validateAdmin(userId,pass);
        System.out.println("isSuccess："+isSuccess);
        if(isSuccess == 0){
            Teachermsg teachermsg = teacherMsgService.findTeacherDetailByAdmin(userId);
            HttpSession sess = request.getSession();
            sess.setAttribute("userId",userId);
            sess.setAttribute("tname",teachermsg.getTname());
            sess.setAttribute("role",teachermsg.getRole());
        }
        JSONObject ja = new JSONObject();
        ja.put("isSuccess",isSuccess);
        System.out.println("test:"+ja.toString());
        return ja;
    }


    /*修改密码*/
    @RequestMapping(value="modifyPassword",method= RequestMethod.POST)
    @ResponseBody
    public Object modifyPassword(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String tid = request.getParameter("userId");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        if(teacherMsgService.loginValidate(tid,oldPassword) == 2){
            js.put("isSuccess", 2);
            return js;
        }
        //返回0成功，1出错
        int isSuccess = teacherMsgService.modifyPassword(tid,newPassword);
        js.put("isSuccess", isSuccess);
        return js;
    }


    //获取教师信息（后台管理）
    @RequestMapping(value="getTeacherMsg",method= RequestMethod.POST)
    @ResponseBody
    public Object getTeacherMsg(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String tname = request.getParameter("tname");
        List<Teachermsg> teachermsg = teacherMsgService.searchTeacherMsg(tname);

        JSONObject js = new JSONObject();
        js.put("tmsg",teachermsg);
        return js;
    }

    //添加教师信息（后台管理）
    @RequestMapping(value="addTeacherMsg",method= RequestMethod.POST)
    @ResponseBody
    public Object addTeacherMsg(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String tid = request.getParameter("tid");
        String password = request.getParameter("password");
        String tname = request.getParameter("tname");
        String professinalTitle = request.getParameter("professinalTitle");
        String contactWay = request.getParameter("contactWay");
        String instruction = request.getParameter("instruction");
        String roleStr = request.getParameter("role");

        int role = 0;
        try {
            role = Integer.parseInt(roleStr);
        }catch (Exception e){
            System.out.println(e);
            js.put("isSuccess", 1);
            return js;
        }


        if (tid==null || tid.equals("") || password==null || password.equals("") ||
                tname==null || tname.equals("") || professinalTitle==null || professinalTitle.equals("") ||
                contactWay==null || contactWay.equals("") || instruction==null || instruction.equals("") ||
                roleStr==null || roleStr.equals("")){
            js.put("isSuccess", 1);
            return js;
        }

        Teachermsg teachermsg = new Teachermsg();
        teachermsg.setTid(tid);
        teachermsg.setTname(tname);
        teachermsg.setPassword(MD5Utils.md5Password(password));
        teachermsg.setProfessinalTitle(professinalTitle);
        teachermsg.setContactWay(contactWay);
        teachermsg.setInstruction(instruction);
        teachermsg.setRole(role);

        //返回0成功，1出错，2冲突
        int isSuccess = teacherMsgService.addTeacherMsg(teachermsg);
        js.put("isSuccess", isSuccess);
        return js;
    }

    //获取教师详细信息（后台管理）
    @RequestMapping(value="getTmDetail.do",method= RequestMethod.POST)
    @ResponseBody
    public Object getTmDetail(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String tid = request.getParameter("tid");
        Teachermsg teachermsg = teacherMsgService.findTeacherDetailByAdmin(tid);
        js.put("teachermsg", teachermsg);
        return js;
    }

    //添加教师信息（后台管理）
    @RequestMapping(value="updateTmDetail",method= RequestMethod.POST)
    @ResponseBody
    public Object updateTmDetail(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String tid = request.getParameter("tid");
        String statusStr = request.getParameter("status");
        String tname = request.getParameter("tname");
        String professinalTitle = request.getParameter("professinalTitle");
        String contactWay = request.getParameter("contactWay");
        String instruction = request.getParameter("instruction");
        String roleStr = request.getParameter("role");

        int status = 0;
        int role = 0;
        try {
            role = Integer.parseInt(roleStr);
            status = Integer.parseInt(statusStr);
        }catch (Exception e){
            System.out.println(e);
            js.put("isSuccess", 1); //1 转换出错
            return js;
        }


        if (tid==null || tid.equals("") || statusStr==null || statusStr.equals("") ||
                tname==null || tname.equals("") || professinalTitle==null || professinalTitle.equals("") ||
                contactWay==null || contactWay.equals("") || instruction==null || instruction.equals("") ||
                roleStr==null || roleStr.equals("")){
            js.put("isSuccess", 1);
            return js;
        }

        Teachermsg teachermsg = new Teachermsg();
        teachermsg.setTid(tid);
        teachermsg.setTname(tname);
        teachermsg.setStatus(status);
        teachermsg.setProfessinalTitle(professinalTitle);
        teachermsg.setContactWay(contactWay);
        teachermsg.setInstruction(instruction);
        teachermsg.setRole(role);

        int isSuccess;
        //返回0成功，1出错，2没有权限
        HttpSession sess = request.getSession();
        //是系统管理员时
        int loginRole = (int) sess.getAttribute("role");
        if( loginRole == 2 ){
            isSuccess = teacherMsgService.updateTeacherMsgBySAdmin(teachermsg);
        }else
            isSuccess = teacherMsgService.updateTeacherMsgByAdmin(teachermsg);

        js.put("isSuccess", isSuccess);
        return js;
    }

    //重置密码（后台管理）
    @RequestMapping(value="resetPassword.do",method= RequestMethod.POST)
    @ResponseBody
    public Object resetPassword(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String tid = request.getParameter("tid");
        boolean isSuccess = teacherMsgService.resetPassword(tid);
        js.put("isSuccess", isSuccess);
        return js;
    }
}
